package com.peak.config.receiver;

import com.peak.service.TestService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 主题型-消息接收监听类
 */
@Slf4j
@Component
public class GeoMQReceiver {
    @Autowired
    private TestService testService;

    /**
     * 默认是单线程监听队列，消息消费会慢
     * 设置concurrency为开启多线程监听队列，concurrency = "5-8"：表示开启5个线程监听队列，最大为8个线程
     */
    @RabbitHandler
    @RabbitListener(queues = "geo.inout.queue", concurrency = "5-8")
    public void process(Map<String,Object> map, Message message, Channel channel) throws IOException {
        try {
            testService.business(map);
            // 手动确认消息
            // 第二个参数，手动确认可以被批处理，当该参数为 true 时，则可以一次性确认 delivery_tag 小于等于传入值的所有消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 确认失败 将消息重新放回队列，让别人消费
            // 第二个参数，true会重新放回队列，所以需要自己根据业务逻辑判断什么时候使用拒绝
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
